package leetcode

//https://leetcode.com/problems/swap-nodes-in-pairs/
//交换每两个相邻的节点
fun main(args: Array<String>) {

}

fun swapPairs(head: ListNode?): ListNode? {

    if (head?.next == null) return head
    var former = head
    var latter = head.next
    var chain: ListNode? = null

    //返回的首节点
    val resultHeader = latter
    while (former != null && latter != null) {
        val tmpNode = latter.next
        latter.next = former
        former.next = tmpNode

        if (chain != null)
            chain.next = latter
        //保留上一个交换对的第二个节点
        chain = former

        former = tmpNode
        latter = tmpNode?.next
    }
    return resultHeader
}